package ee.maoinvest.backend.model.dao.postgresqlimplementations;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import ee.maoinvest.backend.database.ConnectionManager;
import ee.maoinvest.backend.model.dao.ElectricityMeterReadingTypeDAO;
import ee.maoinvest.backend.model.data.ElectricityMeterReadingType;

public class ElectricityMeterReadingTypeDAOPostgresqlImpl implements ElectricityMeterReadingTypeDAO
{
	Logger logger = Logger.getLogger(ElectricityMeterReadingTypeDAOPostgresqlImpl.class);
	Connection dbConnection;
	String sql;
	PreparedStatement preparedStatement;
	Statement statement;
	ResultSet resultSet;
	
	public ElectricityMeterReadingTypeDAOPostgresqlImpl(Connection dbConnection)
	{
		this.dbConnection = dbConnection;
	}
	
	
	@Override
	public List<ElectricityMeterReadingType> getAllElectricityMeterReadingTypes()
	{
		List<ElectricityMeterReadingType> listOfAllElectricityMeterReadingTypes = new ArrayList<ElectricityMeterReadingType>();
		sql = "SELECT * FROM Electricity_meter_reading_types";
		
		try 
		{
			preparedStatement = dbConnection.prepareStatement(
					sql,
					ResultSet.TYPE_SCROLL_INSENSITIVE,
					ResultSet.CONCUR_READ_ONLY
				);
			
			logger.info(preparedStatement.toString());
			resultSet = preparedStatement.executeQuery();
			//place the cursor at the beginning of the result set. Otherwise it can not start reading the result set. 
			resultSet.beforeFirst();
			
			while (resultSet.next())
			{	
				ElectricityMeterReadingType electricityMeterReadingType = new ElectricityMeterReadingType();
				electricityMeterReadingType.setElectricityMeterReadingTypeID(resultSet.getInt("electricityMeterReadingTypeID"));
				electricityMeterReadingType.setTypeName(resultSet.getString("typeName"));
				
				listOfAllElectricityMeterReadingTypes.add(electricityMeterReadingType);
			}
		} 
		catch (SQLException e) 
		{
			logger.error(e.getMessage());
		}
		finally
		{
			ConnectionManager.getInstance().closeStatement(preparedStatement);
			ConnectionManager.getInstance().closeResultSet(resultSet);
		}
		
		return listOfAllElectricityMeterReadingTypes;
	}
}
